﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WorldBankBBS.Comms;
using WorldBankBBS.Logic;
using WorldBankBBS.Resources;
using WorldBankBBS.Translators;

namespace WorldBankBBS.Handlers
{
    public class PauseHandler
    {
        private Session _session = null;
        public PauseHandler(Session session)
        {
            _session = session;
        }

        public static void OnPause(object s, Session args)
        {
            ITranslator translator = null;
            var l = 0;
            var buffer = new byte[100];
            if (args.Encoding == "ASCII")
            {
                translator = new AsciiTranslator() { CurrentSession = args };
                l = translator.StringToBytes(buffer, StringTable.PAUSE1);
                args.Connection.SendData(buffer, 0, l);
            }
            else if (args.Encoding == "ANSI")
            {
                translator = new AnsiTranslator() { CurrentSession = args };
            }
            else if (args.Encoding == "PETSCII")
            {
                translator = new CbmTranslator() { CurrentSession = args };
            }

            var index = 1;
            while (!args.Connection.HasData)
            {
                if (args.Encoding != "ASCII")
                {
                    l = translator.ResourceToBytes(buffer, "PAUSE" + index++);
                    args.Connection.SendData(buffer, 0, l);

                    l = translator.StringToBytes(buffer, "{%LEFT6}");
                    args.Connection.SendData(buffer, 0, l);

                    if (index == 7) index = 1;
                }
                Thread.Sleep(250);
            }

            buffer = new byte[args.Connection.WaitingBytes];

            args.Connection.ReadData(buffer, 0, buffer.Length);

            if (buffer[0] == 1)
            {
                args["PauseAborted"] = true;
                return;
            }

            args.Connection.Clear();
            args["PauseAborted"] = false;
        }
    }
}
